import React, { useState, useRef, useEffect, useCallback } from 'react'
import { useBreakpoint } from '@/hooks/useBreakpoint'
import './style.css'

interface VirtualListProps<T> {
  items: T[]
  itemHeight: number
  containerHeight: number
  renderItem: (item: T, index: number) => React.ReactNode
  overscan?: number
  className?: string
  onScroll?: (scrollTop: number) => void
}

/**
 * 虚拟滚动列表组件
 * Story 3: Task 9 - 性能优化
 * 用于长列表优化，只渲染可见区域的项目
 */
function VirtualList<T>({
  items,
  itemHeight,
  containerHeight,
  renderItem,
  overscan = 3,
  className = '',
  onScroll
}: VirtualListProps<T>) {
  const [scrollTop, setScrollTop] = useState(0)
  const containerRef = useRef<HTMLDivElement>(null)
  const breakpoint = useBreakpoint()
  const isMobile = breakpoint === 'mobile'

  // 计算可见范围
  const visibleStart = Math.floor(scrollTop / itemHeight)
  const visibleEnd = Math.ceil((scrollTop + containerHeight) / itemHeight)

  // 加上 overscan
  const start = Math.max(0, visibleStart - overscan)
  const end = Math.min(items.length, visibleEnd + overscan)

  // 可见项
  const visibleItems = items.slice(start, end)

  // 总高度
  const totalHeight = items.length * itemHeight

  // 滚动处理
  const handleScroll = useCallback((e: React.UIEvent<HTMLDivElement>) => {
    const scrollTop = e.currentTarget.scrollTop
    setScrollTop(scrollTop)
    onScroll?.(scrollTop)
  }, [onScroll])

  // 触摸滚动优化
  useEffect(() => {
    if (!containerRef.current || !isMobile) return

    const container = containerRef.current
    container.style.webkitOverflowScrolling = 'touch'

    return () => {
      container.style.webkitOverflowScrolling = 'auto'
    }
  }, [isMobile])

  return (
    <div
      ref={containerRef}
      className={`virtual-list-container ${className}`}
      style={{ height: containerHeight, overflow: 'auto' }}
      onScroll={handleScroll}
    >
      <div
        className="virtual-list-spacer"
        style={{ height: totalHeight }}
      >
        <div
          className="virtual-list-items"
          style={{
            transform: `translateY(${start * itemHeight}px)`
          }}
        >
          {visibleItems.map((item, index) => (
            <div
              key={start + index}
              className="virtual-list-item"
              style={{ height: itemHeight }}
            >
              {renderItem(item, start + index)}
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}

export default VirtualList
